using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

/// <summary>
/// Summary description for UserPool
/// </summary>
/// 

public class AreaGrid : List<User>
{
    SortedList<DateTime, Message> messages;
    public AreaGrid()
    {
        messages = new SortedList<DateTime, Message>();
    }
    public SortedList<DateTime, Message> Messages { get { return messages; } }
}

public class GridPool: SortedList<int,SortedList<int,AreaGrid>>
{    
	public GridPool()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public void Add(User u)
    {
        lock (this)
        {
            Location loc = u.Location;
            int[] locInMiles = Geographics.ConvertToMiles(loc.Longitude,loc.Latitude);
            int vertiMile = locInMiles[0];
            int horiMile = locInMiles[1];

            if (this.IndexOfKey(vertiMile) >= 0) //if some one is already in that column of longitude
            //which means the column has already been created
            {
                if (this[vertiMile].IndexOfKey(horiMile) < 0)
                    this[vertiMile].Add(horiMile, new AreaGrid());
            }
            else
            {
                this.Add(vertiMile, new SortedList<int, AreaGrid>());
                this[vertiMile].Add(horiMile, new AreaGrid());
            }
            ////////////////////////////////////////
            //this[vertiMile][horiMile].Add(u);
            ////////////////////////////////////////
            u.LocationInPool = new User.PoolLocation(this[vertiMile], this[vertiMile][horiMile]);
        }
    }

    public List<AreaGrid> GetGrids(Location location, int range)
    {
        List<AreaGrid> result = new List<AreaGrid>();
        List<int[]> locations = Geographics.getGridCoordinatesWithinRange(range, location.Longitude, location.Latitude);
        foreach (int[] item in locations)
        {
            if (this.IndexOfKey(item[0]) >= 0)
                if (this[item[0]].IndexOfKey(item[1]) >= 0)
                    result.Add(this[item[0]][item[1]]);
        }
        return result;
    }


    public void Remove(User u)
    {
        Location loc = u.Location;
        int[] locInMiles = Geographics.ConvertToMiles(loc);
        this[locInMiles[0]][locInMiles[1]].Remove(u);
    }
}
